package com.geek.novel.services

import com.geek.novel.entity.BookDownload
import com.geek.novel.entity.BookSection
import com.geek.novel.utils.GsonUtil
import com.geek.novel.vo.Pager
import com.vicpin.krealmextensions.*
import io.realm.Realm
import io.realm.Sort

/**书籍缓存的数据库服务类*/
class BookDownloadRepository private constructor(){

	/**单例模式*/
	companion object{
		@Volatile
		private var instance: BookDownloadRepository? = null
		fun getInstance(): BookDownloadRepository {
			if(instance == null){
				synchronized(BookDownloadRepository::class.java){
					if(instance == null){
						instance = BookDownloadRepository()
					}
				}
			}
			return instance!!
		}
	}

	/**保存*/
	fun save(entity: BookDownload){
		entity.save()
	}

	/**
	 * 删除
	 */
	fun deleteById(id: Long){
		BookDownload().delete { equalTo("id", id) }
	}

	/**保存List*/
	fun saveAll(list: List<BookDownload>){
		val jsonList = GsonUtil.toJson(list)
		val realm = Realm.getDefaultInstance()
		//开启事务，然后批量保存
		realm.executeTransaction {
			it.createOrUpdateAllFromJson(BookDownload::class.java, jsonList)
		}
	}

	/**获取正在缓存中的数据*/
	fun findByBookIdAndCrawlerId(bookId: String, bookCrawlerId: Long): BookDownload? {
		return BookDownload().queryFirst{ equalTo("bookId", bookId).equalTo("bookCrawlerId", bookCrawlerId ) }
	}

	/**获取正在缓存中的数据*/
	fun findDownloadingBook(): List<BookDownload> {
		val query = Realm.getDefaultInstance().where(BookDownload::class.java)
		return query.equalTo("status", "0").findAll()
	}

	/**获取正在缓存中的数据-分页*/
	fun findDownloadingBookPage(lastId: Long, size: Int): Pager<BookDownload> {
		val pager = Pager<BookDownload>()
		pager.pageNo = 0
		pager.size = size

		val count = BookDownload().count()

		val result = BookDownload().query { val query = sort("id", Sort.DESCENDING)
			if(lastId > 0L){
				query.lessThan("id", lastId)
			}
			query.limit(size.toLong()) }

		pager.total = count
		pager.records = result

		return pager
	}

}